from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from index.Anchor import Anchor
from update.UploadFileForm import UploadFileForm
import pandas as pd
import json
import os
import datetime
import time
from index.models import Data


# Create your views here.

def index(request):
    result = {
        "code": 200,
        "msg": "error",
        "data": ""
    }
    return HttpResponse(json.dumps(result))


def upload_file(request):
    if request.method == 'POST':
        f1 = request.FILES.get("file", None)
        name = request.POST.get("name")
        email = request.POST.get("email")
        company_name = request.POST.get("company")
        openid = request.POST.get("openid")

        if not f1:
            print("upload file is error")

        ticks = time.time()
        date_str = time.strftime("%Y_%m_%d", time.gmtime(ticks))
        dirs = os.path.join(os.getcwd() + "/media/" + date_str)
        if not os.path.exists(dirs):
            os.makedirs(dirs)

        date_str_dh = time.strftime("%Y_%m_%d_%H_%M_%S", time.gmtime(ticks))
        file_name = openid + date_str_dh + ".csv"
        file_path = os.getcwd() + "/media/" + date_str + "/" + file_name
        print(file_path)
        destination = open(os.path.join(os.getcwd() + "/media/" + date_str + "/", file_name), 'wb+')
        for chunk in f1.chunks():
            destination.write(chunk)

        destination.close()

        anchor = Anchor()
        result_data = anchor.anchor_file_data(openid, file_path)
        en_file_name = result_data[0]
        ch_file_name = result_data[1]
        y_predict = result_data[2]
        cvs_df = result_data[3]

        # 第1列
        n1 = cvs_df.iloc[:, 0]
        data_n1 = getDataRow(n1)

        n2 = cvs_df.iloc[:, 1]
        data_n2 = getDataRow(n2)

        lembed = cvs_df.iloc[:, 2]
        data_lembed = getDataRow(lembed)

        lbond = cvs_df.iloc[:, 3]
        data_lbond = getDataRow(lbond)

        ahole = cvs_df.iloc[:, 4]
        data_ahole = getDataRow(ahole)

        n = cvs_df.iloc[:, 5]
        data_n = getDataRow(n)

        ea = cvs_df.iloc[:, 6]
        data_ea = getDataRow(ea)

        v = cvs_df.iloc[:, 7]
        data_v = getDataRow(v)

        pg1 = cvs_df.iloc[:, 8]
        data_pg1 = getDataRow(pg1)

        pg2 = cvs_df.iloc[:, 9]
        data_pg2 = getDataRow(pg2)

        pmax = cvs_df.iloc[:, 10]
        data_pmax = getDataRow(pmax)

        data = Data()
        data.open_id = openid
        data.data_n1 = data_n1
        data.data_n2 = data_n2
        data.data_lembed = data_lembed
        data.data_lbond = data_lbond
        data.data_ahole = data_ahole
        data.data_n = data_n
        data.data_ea = data_ea
        data.data_v = data_v
        data.data_pg1 = data_pg1
        data.data_pg2 = data_pg2
        data.data_pmax = data_pmax
        data.name = name
        data.email = email
        data.company = company_name
        data.up_file_name = "/media/" + date_str + "/" + file_name

        data.en_file_name = en_file_name
        data.ch_file_name = ch_file_name

        predict = ""
        for i in range(len(y_predict)):
            print(y_predict[i])
            ll = len(y_predict) - 1
            if i == ll:
                if y_predict[i] < 0:
                    y_predict[i] = 0
                predict = predict + str(y_predict[i])
            else:
                if y_predict[i] < 0:
                    y_predict[i] = 0
                predict = predict + str(y_predict[i]) + ","

        data.y_predict = predict
        data.is_more = 1
        data.status = 1
        data.create_id = openid
        data.save()

        result_d = {
            "en_file": en_file_name,
            "ch_file": ch_file_name,
            "y_predict": predict,
        }
        data = {
            "code": 1,
            "msg": "计算成功！",
            "data": result_d,
        }
        result = {
            "code": 200,
            "msg": "ok",
            "data": data
        }
        return HttpResponse(json.dumps(result, default=DateEncoder))
    else:
        data = {
            "code": 0,
            "msg": "计算失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": data
        }
        return HttpResponse(json.dumps(result))


def getDataRow(data):
    data_d = ""
    for i in range(len(data)):
        ll = len(data) - 1
        if i == ll:
            data_d = data_d + str(data[i])
        else:
            data_d = data_d + str(data[i]) + ","
        if i == 20:
            data_d = data_d + str(data[i]) + "......"
            break
    return data_d


def DateEncoder(obj):
    if isinstance(obj, (datetime.datetime, datetime.date)):
        return obj.strftime('%Y-%m-%d')
